#include "OneWire.h"
#include <REGX52.H>


#define DS18B20_SKIP_ROM 0xCC
#define DS18B20_CONVERT_T 0x44
#define DS18B20_READ_SCRATCHPAD 0xBE
#define DS18B20_WRITE_SCRATCHPAD 0x4E
#define DS18B20_COPY_SCRATCHPAD 0x48

/**
  * @brief   进行温度转换
  * @details 
  * @param   
  * @retval  
  */
void DS18B20_ConvertT() {
	OneWire_Init();
	OneWire_SendByte(DS18B20_SKIP_ROM);
	OneWire_SendByte(DS18B20_CONVERT_T);
}

/**
  * @brief   读取温度
  * @details 如为负数直接*-1可得其正数，右移四位为整数部分，低四位*625可得小数的十进制，读取过程需注意时序不要被打断
  * @param   
  * @retval  int 包含符号位的温度，低四位为小数，接着七位为整数，剩余5位高位为符号位
  */
int DS18B20_ReadTemp() {
	int temp;
	OneWire_Init();
	OneWire_SendByte(DS18B20_SKIP_ROM);
	OneWire_SendByte(DS18B20_READ_SCRATCHPAD);
	temp = OneWire_ReceiveByte();
	temp |= OneWire_ReceiveByte() << 8;
	return temp;
}

/**
  * @brief   读取DS18B20 TH TL寄存器
  * @details 高八位为TH，低八位为TL
  * @param   
  * @retval  
  */
unsigned int DS18B20_ReadTempLimit() {
	unsigned int limit;
	OneWire_Init();
	OneWire_SendByte(DS18B20_SKIP_ROM);
	OneWire_SendByte(DS18B20_READ_SCRATCHPAD);
	OneWire_ReceiveByte();
	OneWire_ReceiveByte();
	limit = OneWire_ReceiveByte() << 8;
	limit |= OneWire_ReceiveByte();
	return limit;
}

/**
  * @brief   写入数据到TH,TL寄存器，并写入到DS18B20的EEPROM
  * @details 
  * @param   th TH寄存器的值
  * @param   tl TL寄存器的值
  * @retval  
  */
void DS18B20_WriteTempLimit(char th, char tl) {
	OneWire_Init();
	OneWire_SendByte(DS18B20_SKIP_ROM);
	OneWire_SendByte(DS18B20_WRITE_SCRATCHPAD);
	OneWire_SendByte(th);	// 写入最高阈值
	OneWire_SendByte(tl);	// 写入最低阈值
	OneWire_SendByte(0x7FFF);	// 写入配置寄存器，默认12分辨率 即0.0625
	OneWire_Init();
	OneWire_SendByte(DS18B20_SKIP_ROM);
	OneWire_SendByte(DS18B20_COPY_SCRATCHPAD);
}